package com.hxzy.fileupload.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.hxzy.fileupload.service.IFileUploadService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;

/**
 * fastdfs上传
 */
@Service
public class FastDfsFileUploadServiceImpl implements IFileUploadService {


    /**
     * 域名或本机访问地址
     */
    @Value("${fdfs.domain}")
    public String domain;

    @Autowired
    private FastFileStorageClient storageClient;


    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        // 得到上传文件原始文件名      文件名.后缀名
        String ext=file.getOriginalFilename();

        //bloc没有文件名，上传的是二进制的数据
        if(ext.equalsIgnoreCase("blob")){
            ext=ext+"."+contentTypeFindExt(file.getContentType());
        }

        // fastdfs上传代码
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(ext), null);
        return domain + "/" + storePath.getFullPath();

    }

    /**
     * 文件上传并生成缩略图
     * @param file 上传的文件
     * @return
     * @throws Exception
     */
    @Override
    public String uploadImageAndCrtThumbImage(MultipartFile file) throws Exception {
        // 得到上传文件原始文件名      文件名.后缀名
        String ext=file.getOriginalFilename();

        //bloc没有文件名，上传的是二进制的数据
        if(ext.equalsIgnoreCase("blob")){
            ext=ext+"."+contentTypeFindExt(file.getContentType());
        }

        // fastdfs上传代码
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(ext), null);
        return domain + "/" + storePath.getFullPath();
    }


    /**
     *  根据 mimetype获取是什么样的文件后缀
     * @param contentType
     * @return
     */
    public String contentTypeFindExt(String contentType){
        for(String key : fileExtensionToMediaTypes.keySet()){
            List<MediaType> mediaTypes = fileExtensionToMediaTypes.get(key);
            long count = mediaTypes.stream().filter(p -> p.toString().equalsIgnoreCase(contentType)).count();

            if(count>0){
                return key;
            }
        }
        return "tmp";
    }
    private static final MultiValueMap<String, MediaType> fileExtensionToMediaTypes = parseMimeTypes();



    private static MultiValueMap<String, MediaType> parseMimeTypes() {
        InputStream is = MediaTypeFactory.class.getResourceAsStream("/org/springframework/http/mime.types");
        Assert.state(is != null, "/org/springframework/http/mime.types not found in classpath");

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.US_ASCII));
            Throwable var2 = null;

            try {
                LinkedMultiValueMap result = new LinkedMultiValueMap();

                label122:
                while(true) {
                    String line;
                    if ((line = reader.readLine()) != null) {
                        if (line.isEmpty() || line.charAt(0) == '#') {
                            continue;
                        }

                        String[] tokens = StringUtils.tokenizeToStringArray(line, " \t\n\r\f");
                        MediaType mediaType = MediaType.parseMediaType(tokens[0]);
                        int i = 1;

                        while(true) {
                            if (i >= tokens.length) {
                                continue label122;
                            }

                            String fileExtension = tokens[i].toLowerCase(Locale.ENGLISH);
                            result.add(fileExtension, mediaType);
                            ++i;
                        }
                    }

                    LinkedMultiValueMap var5 = result;
                    return var5;
                }
            } catch (Throwable var17) {
                var2 = var17;
                throw var17;
            } finally {
                if (reader != null) {
                    if (var2 != null) {
                        try {
                            reader.close();
                        } catch (Throwable var16) {
                            var2.addSuppressed(var16);
                        }
                    } else {
                        reader.close();
                    }
                }

            }
        } catch (IOException var19) {
            throw new IllegalStateException("Could not read /org/springframework/http/mime.types", var19);
        }
    }
}
